<template>
  <a-card
    :bordered="false"
    style="min-height: 100%"
    :bodyStyle="{ 'text-align': 'center', height: '100%' }"
    @click="cc"
  >
    <div class="content">
      <div class="top" @click="forgetVisible = true">忘记带卡?</div>
      <div class="cardClockInArea">
        <div class="left">
          <!-- 刷卡初始 -->
          <div style="width: 100%; text-align: center; height: 240px; background-color: #fff" v-if="!info">
            <img
              src="~@/assets/img/qingshuka.png"
              style="position: absolute; top: 65px; left: 15px"
              v-if="showfont == ''"
            />
            <img
              src="~@/assets/img/wuxiao.png"
              style="position: absolute; top: 65px; left: 15px"
              v-if="showfont == '无效卡'"
            />
            <img
              src="~@/assets/img/cantshuaka.png"
              style="position: absolute; top: 65px; left: 15px"
              v-if="showfont == '一分钟内不允许重复刷卡'"
            />
          </div>
          <!-- 无效卡 -->

          <div v-if="info" class="have-student">
            <img src="~@/assets/img/chenggong.png" />
            <div style="margin-top: 15px">{{ info.student.name }}</div>
          </div>
          <div class="chenggong" v-if="showfont != '' && info">{{ showfont }}</div>
          <div
            class="wuxiao"
            v-if="showfont != '' && !info"
            :class="{ oneminute: showfont == '一分钟内不允许重复刷卡' }"
          >
            {{ showfont }}
          </div>
        </div>
        <div class="right">
          <img src="~@/assets/img/bigcard.png" alt />
          <p style="line-height: 30px; text-align: center; color: #b0b0b0">请刷卡</p>
        </div>
      </div>
      <div class="count">
        <div class="left">
          今日待签到学员数
          <a @click="lookToday">{{ peoples.wait_to_sign_in }}</a>
        </div>
        <div class="right">
          今日待签退学员数
          <a @click="lookTodayOut">{{ peoples.wait_to_sign_out }}</a>
        </div>
      </div>
      <!-- <div class="copyRight">刷卡机仅支持在Windows系统的电脑上使用</div> -->
    </div>
    <input type="text" id="cardClockIn" v-model="text" />
    <input type="text" id="idcards_input" v-model="idcard_input" />
    <!-- <input type="text" id="cardClockIna" v-model="text" /> -->
    <!-- 今日待签到学员数 -->
    <a-modal
      title="今日待签到学员"
      :visible="todayInVisible"
      @cancel="todayInVisible = false"
      :footer="null"
      :width="900"
    >
      <a-spin :spinning="spinningStatus">
        <div>凌晨0点后创建的今日排课、审批通过的今日请假不纳入待签到统计范围内</div>
        <a-table
          ref="table"
          size="default"
          rowKey="key"
          :columns="todaycolumns"
          :data-source="loadData"
          style="margin-top: 10px"
          class="user_management_table"
          :pagination="false"
          :scroll="{ y: 400 }"
        >
          <span slot="face_status" slot-scope="text, record" style="cursor: pointer">
            <span @click="goFace(record)">
              <span v-if="record.faces.length > 0">
                <span class="iconfont icon-renlianshibie" style="font-size: 22px; color: rgb(74, 183, 141)"></span>
              </span>
              <span v-else>
                <span class="iconfont icon-renlianshibie" style="font-size: 22px; color: rgb(191, 191, 191)"></span>
              </span>
            </span>
          </span>
          <span slot="class_name" slot-scope="text, record">
            <div v-if="record.schedules.data.length > 0">
              <div
                v-for="(item, index) in record.schedules.data"
                :key="index"
                :class="{ borderbtm: record.schedules.data.length > 1 }"
              >
                {{ item.class_start_time }}-{{ item.class_end_time }} {{ item.class_name }}
              </div>
            </div>
            <div v-else>-</div>
          </span>
          <span slot="id_card" slot-scope="text, record">
            <div style="cursor: pointer">
              <span v-if="!record.card_num" @click="addIdCard(record)">
                <a-icon type="idcard" style="color: rgb(191, 191, 191); font-size: 22px" />
              </span>
              <span v-else><a-icon type="idcard" style="color: rgb(74, 183, 141); font-size: 22px" /></span>
            </div>
          </span>
          <span slot="min_time" slot-scope="text, record">
            <span v-if="record.schedules.min_time">{{ record.schedules.min_time }}</span>
            <span v-else>-</span>
          </span>
          <span slot="NoSignin" slot-scope="text, record">
            <a @click="buqian(record)">签到补卡</a>
          </span>
        </a-table>
        <div style="margin-top: 10px; text-align: right" v-if="pages.pagination">
          <a-pagination v-model="newPage" :total="pages.pagination.total" @change="addPages" />
        </div>
      </a-spin>
    </a-modal>
    <a-modal
      :visible="Visible"
      @cancel="Visible = false"
      :width="400"
      @ok="handleOk"
      :confirm-loading="buqianconfirmLoading"
      :z-index="1001"
    >
      <span slot="title">{{ buqianType == 1 ? '签到' : '签退' }}补卡确认</span>
      <div style="margin: 10px 0 20px">
        将 <a v-if="signInData">{{ signInData.name }}</a> 的签到刷卡时间标记为
      </div>
      <div>
        {{ today }}
        <a-time-picker v-model="buqianTime" format="HH:mm" />
      </div>
    </a-modal>
    <!-- 今日待签退学员数 -->
    <a-modal
      title="今日待签退学员"
      :visible="todayOutVisible"
      @cancel="todayOutVisible = false"
      :footer="null"
      :width="900"
    >
      <a-spin :spinning="spinningStatus">
        <a-table
          ref="table"
          size="default"
          rowKey="key"
          :columns="todaycolumns1"
          :data-source="loadData"
          style="margin-top: 10px"
          class="user_management_table"
          :pagination="false"
          :scroll="{ y: 400 }"
        >
        <span slot="face_status" slot-scope="text, record" style="cursor: pointer">
            <span @click="goFace(record)">
              <span v-if="record.faces.length > 0">
                <span class="iconfont icon-renlianshibie" style="font-size: 22px; color: rgb(74, 183, 141)"></span>
              </span>
              <span v-else>
                <span class="iconfont icon-renlianshibie" style="font-size: 22px; color: rgb(191, 191, 191)"></span>
              </span>
            </span>
          </span>
          <span slot="id_card" slot-scope="text, record">
            <div style="cursor: pointer">
              <span v-if="!record.card_num" @click="addIdCard(record)">
                <a-icon type="idcard" style="color: rgb(191, 191, 191); font-size: 22px" />
              </span>
              <span v-else><a-icon type="idcard" style="color: rgb(74, 183, 141); font-size: 22px" /></span>
            </div>
          </span>
          <span slot="sign_in_time" slot-scope="text, record">
            <span v-if="record.sign_in_time">{{ record.sign_in_time | times('hh:mm') }}</span>
            <span v-else>-</span>
          </span>
          <span slot="NoSignin" slot-scope="text, record">
            <a @click="buqian1(record)">签退补卡</a>
          </span>
        </a-table>
        <div style="margin-top: 10px; text-align: right" v-if="pages.pagination">
          <a-pagination v-model="newPage1" :total="pages.pagination.total" @change="addPages1" />
        </div>
      </a-spin>
    </a-modal>
    <!-- 添加 绑定卡 -->
    <a-modal
      title="绑定卡片"
      :visible="cardVisible"
      :footer="null"
      @cancel="cardVisible = false"
      width="400px"
      :z-index="1001"
    >
      <div v-if="!idCardData.card_num" style="width: 100%; text-align: center" @click="oncad">
        <img src="~@/assets/img/bigcard.png" alt="" style="width: 50%" />
        <div>请刷卡</div>
      </div>
    </a-modal>
    <!-- 忘记带卡 -->
    <a-modal
      title="忘记带卡"
      :visible="forgetVisible"
      :confirm-loading="confirmLoading"
      @cancel="forgetQuxiao"
      :width="400"
      @ok="teacherSign"
    >
      <div>以当前系统时间作为学员的刷卡时间</div>
      <div style="margin-top: 15px; cursor: pointer" @click="lookForget">
        选择学员
        <a-icon type="down" />
      </div>
      <div v-if="studentInfo" style="margin-top: 15px">
        <img :src="studentInfo.head_portrait.url" style="width: 35px; height: 35px; border-radius: 25px" />
        <div style="margin-top: 10px; margin-left: 5px">{{ studentInfo.name }}</div>
      </div>
    </a-modal>
    <!-- 考勤列表 -->
    <a-modal
      title="考勤学员列表"
      :visible="kaoqinVisible"
      @cancel="kaoqinVisible = false"
      :width="600"
      @ok="studenthandleOk"
    >
      <div>
        <a-input-search style="width: 168px" placeholder="学员姓名" />
      </div>
      <div style="margin-top: 10px">
        <a-table
          :columns="studentColumns"
          :data-source="StudentData"
          :pagination="false"
          class="user_management_table"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio' }"
          :scroll="{ y: 260 }"
        ></a-table>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { payByCard, statisticsPeople, todayList, studentList, teacherSign, addIdCard } from '@/api/classconsumes'
import moment from 'moment'
import { STable } from '@/components'
import { _debounce } from '@/utils/domUtil'
import { appCenterList } from '@/api/lives'
export default {
  components: {
    STable,
  },
  name: 'bycard',
  data() {
    return {
      cardVisible: false,
      idcard_input: '',
      confirmLoading: false,
      buqianconfirmLoading: false,
      selectedRowKeys: [],
      selectedData: [],
      studentInfo: undefined,
      studentColumns: [
        {
          title: '学员姓名',
          dataIndex: 'name',
        },
      ],

      StudentData: [],
      kaoqinVisible: false,
      forgetVisible: false,
      spinningStatus: false,
      todayInVisible: false,
      Visible: false,
      todayOutVisible: false,
      text: '',
      flag: false,
      showfont: '',
      info: undefined,
      peoples: {},
      buqianTime: null,
      todaycolumns: [
        {
          title: '学员姓名',
          dataIndex: 'name',
        },
        {
          title: '手机号',
          dataIndex: 'main_phone',
          width:150
        },
        {
          title: '考勤卡',
          scopedSlots: { customRender: 'id_card' },
          align: 'center',
        },
        {
          title: '今日排课',
          scopedSlots: { customRender: 'class_name' },
          width: 200,
        },
        {
          title: '待签到时间',
          scopedSlots: { customRender: 'min_time' },
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'NoSignin' },
        },
      ],
      todaycolumns1: [
        {
          title: '学员姓名',
          dataIndex: 'name',
        },
        {
          title: '手机号',
          dataIndex: 'main_phone',
           width:150
        },
        {
          title: '考勤卡',
          scopedSlots: { customRender: 'id_card' },
          align: 'center',
        },
        // {
        //   title: '今日排课',
        //   scopedSlots: { customRender: 'sign_in_time' },
        // },
        {
          title: '今日签到时间',
          scopedSlots: { customRender: 'sign_in_time' },
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'NoSignin' },
        },
      ],
      loadData: [],
      newPage: 1,
      newPage1: 1,
      newPage2: 1,
      pages: {},
      signInData: {},
      today: moment().format('YYYY-MM-DD'),
      buqianType: 1,
      idCardData: {
        card_num: null,
      },
    }
  },
  watch: {
    text(newValue, oldValue) {
      document.querySelector('#cardClockIn').focus()
      if (newValue != '') {
        this.cardTj()
      }
    },
    idcard_input(newValue, oldValue) {
      document.querySelector('#idcards_input').focus()
      if (newValue != '') {
        this.cardTj1()
      }
    },
  },
  methods: {
    cardTj: _debounce(function () {
      this.submit()
    }, 500),
    cardTj1: _debounce(function () {
      this.addSubmit()
    }, 500),

    //添加卡片
    oncad() {
      document.querySelector('#idcards_input').focus()
    },
    addIdCard(data) {
      this.idCardData = data
      this.cardVisible = true
      setTimeout(() => {
        document.querySelector('#idcards_input').focus()
      }, 500)
    },
    //没有添加刷卡 卡号
    addSubmit() {
      addIdCard(this.idCardData.id, { card_num: this.idcard_input })
        .then((res) => {
          this.idcard_input = ''
          this.cardVisible = false
          this.lookToday()
          this.$message.success('添加卡号成功')
        })
        .catch((err) => {
          this.idcard_input = ''
          this.$message.error(err.data.message || '刷卡失败，请刷新后重试')
        })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedData = selectedRows
    },
    moment,
    checked() {
      document.querySelector('#cardClockIn').focus()
    },
    cc() {
      document.querySelector('#cardClockIn').focus()
    },
    submit() {
      if (this.flag == false) {
        this.flag = true
        payByCard({ school_id: this.$store.state.user.school, card_num: this.text })
          .then((res) => {
            this.$message.success('操作成功')
            this.text = ''
            this.flag = false
            if (!res.duration) {
              this.showfont = '签到成功'
            } else {
              this.showfont = '签退成功'
            }

            this.info = res
            this.statistics()
            setTimeout(() => {
              this.showfont = ''
              this.info = undefined
            }, 2000)
          })
          .catch((err) => {
            this.$message.error(err.data.message || '操作失败，请刷新后重试')
            this.showfont = err.data.message
            setTimeout(() => {
              this.showfont = ''
            }, 1000)
            this.text = ''
            this.flag = false
          })
      } else {
        this.$message.error('操作频繁')
        this.text = ''
      }
    },
    forgetQuxiao() {
      this.forgetVisible = false
      this.selectedRowKeys = []
      this.studentInfo = undefined
    },
    //统计签到 签退学员
    statistics() {
      statisticsPeople({ school_id: this.$store.state.user.school })
        .then((res) => {
          this.peoples = res
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败，请刷新后重试')
        })
    },
    lookToday(pageno = 1, pagesize = 10) {
      this.spinningStatus = true
      todayList({ school_id: this.$store.state.user.school, type: 1, pageNo: pageno, pageSize: pagesize })
        .then((res) => {
          this.loadData = res.data
          this.pages = res.meta
          this.todayInVisible = true
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败')
        })
        .finally(() => {
          this.spinningStatus = false
        })
    },
    lookTodayOut(pageno = 1, pagesize = 10) {
      this.spinningStatus = true
      todayList({ school_id: this.$store.state.user.school, type: 2, pageNo: pageno, pageSize: pagesize })
        .then((res) => {
          this.loadData = res.data
          this.pages = res.meta
          this.todayOutVisible = true
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败')
        })
        .finally(() => {
          this.spinningStatus = false
        })
    },
    addPages(page, pageSize) {
      this.newPage = page
      this.lookToday(page, pageSize)
    },
    addPages1(page, pageSize) {
      this.newPage1 = page
      this.lookTodayOut(page, pageSize)
    },
    buqian(data) {
      this.buqianType = 1
      this.signInData = data
      console.log(this.signInData)
      if (this.signInData.schedules.min_time) {
        this.buqianTime = moment(this.signInData.schedules.min_time, 'HH:mm')
      }
      this.Visible = true
    },
    buqian1(data) {
      this.buqianType = 2
      this.signInData = data
      this.buqianTime = moment(moment().format('HH:mm'), 'HH:mm')
      console.log(this.buqianTime)
      this.Visible = true
    },
    lookForget(pageno = 1, pagesize = 10) {
      studentList({ school_id: this.$store.state.user.school, pageNo: pageno, pageSize: pagesize })
        .then((res) => {
          this.StudentData = res
          // this.pages=res.meta
          this.kaoqinVisible = true
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败')
        })
    },
    studenthandleOk() {
      this.kaoqinVisible = false
      this.studentInfo = this.selectedData[0]
    },
    teacherSign() {
      let nowTime = moment().format('YYYY-MM-DD HH:mm')
      if (this.studentInfo) {
        this.confirmLoading = true
        teacherSign({ student_id: this.studentInfo.id, time: nowTime, type: 1 })
          .then((res) => {
            this.statistics()
            this.$message.success('签到成功!')
            this.confirmLoading = false
            this.forgetVisible = false
          })
          .catch((err) => {
            this.confirmLoading = false
            this.$message.error(err.data.message || '签到失败')
          })
      } else {
        this.$message.warning('请选择学生!')
      }
    },
    handleOk() {
      this.buqianconfirmLoading = true
      let time = null
      if (this.buqianTime) {
        time = this.today + ' ' + moment(this.buqianTime).format('HH:mm')
      } else {
        this.$message.warning('请选择时间!')
        this.buqianconfirmLoading = false
        return
      }
      teacherSign({ student_id: this.signInData.id, type: this.buqianType, time: time })
        .then((res) => {
          if (this.buqianType == 1) {
            this.lookToday()
            this.$message.success('签到补卡成功!')
          } else {
            this.lookTodayOut()
            this.$message.success('签退补卡成功!')
          }

          this.Visible = false
          this.buqianconfirmLoading = false
          this.statistics()
        })
        .catch((err) => {
          if (this.buqianType == 1) {
            this.$message.error(err.data.message || '签到补卡失败')
          } else {
            this.$message.error(err.data.message || '签退补卡失败')
          }
          this.buqianconfirmLoading = false
        })
    },
    goFace(data) {
      let routeData = this.$router.resolve({
        name: 'faceClockIn',
        query: { student_id: data.id,student_name:data.name },
      })
      sessionStorage.setItem('store', JSON.stringify(this.$store.state))
      window.open(routeData.href, '_blank')
    },
  },
  mounted() {
    this.checked()
  },
  created() {
    this.statistics()
    let permission = this.$store.getters.roles.permissionList
    if (permission.indexOf('faceList') != -1) {
      this.todaycolumns.splice(3, 0, {
        title: '人脸',
        scopedSlots: { customRender: 'face_status' },
        align: 'center',
      })
      this.todaycolumns1.splice(3, 0, {
        title: '人脸',
        scopedSlots: { customRender: 'face_status' },
        align: 'center',
      })
    }
    // appCenterList({ school_id: this.$store.state.user.school }).then((res) => {
    //   if (res.length > 0) {
    //     res.forEach((item) => {
    //       if (item.key == 'AttendFace') {
    //         this.todaycolumns.splice(3, 0, {
    //           title: '人脸',
    //           scopedSlots: { customRender: 'face_status' },
    //           align: 'center',
    //         })
    //         this.todaycolumns1.splice(3, 0, {
    //           title: '人脸',
    //           scopedSlots: { customRender: 'face_status' },
    //           align: 'center',
    //         })
    //       }
    //     })
    //   }
    // })
  },
}
</script>

<style lang="scss" scoped>
@import '~@/assets/img/customFormIcon/iconfont.css';
.content {
  width: 720px;
  margin: 0 auto;
  padding-top: 30px;
  .top {
    text-align: right;
    color: #2a2a2a;
    padding-right: 4px;
    cursor: pointer;
  }
  .cardClockInArea {
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    .left {
      position: relative;
      width: 205px;
      height: 300px;
      background-color: #fcfcfc;
      float: left;
      border-radius: 10px;
      overflow: hidden;
      -webkit-box-shadow: 0 0 10px #eaeaea;
      box-shadow: 0 0 10px #eaeaea;
    }
    .right {
      width: 450px;
      -webkit-box-shadow: 0 0 10px #eaeaea;
      box-shadow: 0 0 10px #eaeaea;
      border-radius: 10px;
      height: 300px;
      padding-top: 30px;
      text-align: center;
      color: #b0b0b0;
    }
  }
  .count {
    display: flex;
    margin-top: 30px;
    justify-content: space-around;
  }
  .copyRight {
    color: #999;
    margin: 40px auto 50px;
    font-size: 14px;
    text-align: center;
  }
}
#cardClockIn {
  position: relative;
  top: -100000000px;
}
#idcards_input {
  position: relative;
  top: -100000000px;
}
.wuxiao {
  height: calc(100% - 240px);
  background-image: linear-gradient(to right, #f67372, #f0856d);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}
.chenggong {
  height: calc(100% - 240px);
  background-image: linear-gradient(to right, #66d79b, #5ecfa5);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}
.user_management_table {
  border: 1px solid #efefef;
}
.borderbtm {
  // border-bottom: 1px dashed #ada5a5;
  padding-bottom: 10px;
}
.oneminute {
  font-size: 16px;
}
.have-student {
  width: 100%;
  height: 240px;
  background-color: rgb(255, 255, 255);
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}
</style>